var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/public/index.html');
});

function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

io.of('my-room').on('connection', (client) => {
    client.join('room');
    // 监听消息订阅
    client.on('subscribeToMsg', (name) => {
        io.of('my-room').in('room').emit('message', {
            type: 'info',
            author: 'admin',
            content: `${name} 上线了`
        });
    });
    // 接收到客户端发过来的消息
    client.on('clientSendMsg', msg => {
        io.of('my-room').in('room').emit('message', msg);
    });
    // 监听到毫秒级消息发送
    client.on('subscribeInmsec', (interval) => {
        setInterval(() => {
            let arr = [];
            for (let i = 0; i < 10; i++) {
                arr.push({
                    id: Math.ceil(Math.random() * 999),
                    label: randomString(8),
                    value: randomString(18),
                })
            }
            console.log('---data---', arr);
            client.emit('data', arr);
        }, interval);
    });
});

const port = 8000;
io.listen(port);
console.log('listening on port ', port);